{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Congestion Charges - Medium"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading spark-stubs, spark-hive\n",
      "Adding Hive conf dir /opt/hive/conf to classpath\n",
      "Creating SparkSession\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "SLF4J: No SLF4J providers were found.\n",
      "SLF4J: Defaulting to no-operation (NOP) logger implementation\n",
      "SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<a target=\"_blank\" href=\"http://jupyter:4040\">Spark UI</a>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36m$ivy.$                                  \n",
       "\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.log4j.{Level, Logger}\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.types._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.functions._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.expressions.Window\n",
       "\n",
       "\u001b[39m\n",
       "\u001b[36mspark\u001b[39m: \u001b[32mSparkSession\u001b[39m = org.apache.spark.sql.SparkSession@64447db"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import $ivy.`org.apache.spark::spark-sql:3.4.0`\n",
    "\n",
    "import org.apache.log4j.{Level, Logger}\n",
    "Logger.getLogger(\"org\").setLevel(Level.OFF)\n",
    "\n",
    "import org.apache.spark._\n",
    "import org.apache.spark.sql._\n",
    "import org.apache.spark.sql.types._\n",
    "import org.apache.spark.sql.functions._\n",
    "import org.apache.spark.sql.expressions.Window\n",
    "\n",
    "val spark = {\n",
    "    NotebookSparkSession.builder()\n",
    "    .progress(false)\n",
    "    .appName(\"app18-2\")\n",
    "    // .master(\"spark://192.168.31.31:7077\")\n",
    "    .master(\"local[*]\")\n",
    "    .config(\"spark.sql.warehouse.dir\", \n",
    "            \"hdfs://192.168.31.31:9000/user/hive/warehouse\") \n",
    "    .config(\"spark.cores.max\", \"4\") \n",
    "    .config(\"spark.executor.instances\", \"1\") \n",
    "    .config(\"spark.executor.cores\", \"2\") \n",
    "    .config(\"spark.executor.memory\", \"10g\") \n",
    "    .config(\"spark.shuffle.service.enabled\", \"false\") \n",
    "    .config(\"spark.dynamicAllocation.enabled\", \"false\") \n",
    "    .config(\"spark.sql.catalogImplementation\", \"hive\")\n",
    "    .config(\"spark.sql.repl.eagerEval.enabled\", \"true\")\n",
    "    .config(\"spark.driver.allowMultipleContexts\", \"true\")\n",
    "    .getOrCreate()\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36mspark.implicits._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36mspark.sqlContext.implicits._\n",
       "\u001b[39m\n",
       "defined \u001b[32mfunction\u001b[39m \u001b[36msc\u001b[39m\n",
       "\u001b[36mhiveCxt\u001b[39m: \u001b[32msql\u001b[39m.\u001b[32mhive\u001b[39m.\u001b[32mHiveContext\u001b[39m = org.apache.spark.sql.hive.HiveContext@4c5be1c6"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import spark.implicits._\n",
    "import spark.sqlContext.implicits._\n",
    "def sc = spark.sparkContext\n",
    "val hiveCxt = new org.apache.spark.sql.hive.HiveContext(sc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mRichDF\u001b[39m"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// Credit to Aivean\n",
    "implicit class RichDF(val ds:DataFrame) {\n",
    "    def showHTML(limit: Int = 50, truncate: Int = 100) = {\n",
    "        import xml.Utility.escape\n",
    "        val data = ds.take(limit)\n",
    "        val header = ds.schema.fieldNames.toSeq        \n",
    "        val rows: Seq[Seq[String]] = data.map { row =>\n",
    "          row.toSeq.map {cell =>\n",
    "            val str = cell match {\n",
    "              case null => \"null\"\n",
    "              case binary: Array[Byte] => binary.map(\"%02X\".format(_)).mkString(\"[\", \" \", \"]\")\n",
    "              case array: Array[_] => array.mkString(\"[\", \", \", \"]\")\n",
    "              case seq: Seq[_] => seq.mkString(\"[\", \", \", \"]\")\n",
    "              case _ => cell.toString\n",
    "            }\n",
    "            if (truncate > 0 && str.length > truncate) {\n",
    "              // do not show ellipses for strings shorter than 4 characters.\n",
    "              if (truncate < 4) str.substring(0, truncate)\n",
    "              else str.substring(0, truncate - 3) + \"...\"\n",
    "            } else {\n",
    "              str\n",
    "            }\n",
    "          }: Seq[String]\n",
    "        }\n",
    "    publish.html(s\"\"\" <table>\n",
    "                <tr>\n",
    "                 ${header.map(h => s\"<th>${escape(h)}</th>\").mkString}\n",
    "                </tr>\n",
    "                ${rows.map {row =>\n",
    "                  s\"<tr>${row.map{c => s\"<td>${escape(c)}</td>\" }.mkString}</tr>\"\n",
    "                }.mkString}\n",
    "            </table>\n",
    "        \"\"\")\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[36mcamera\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: int, perim: string]\n",
       "\u001b[36mkeeper\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: int, name: string ... 1 more field]\n",
       "\u001b[36mvehicle\u001b[39m: \u001b[32mDataFrame\u001b[39m = [id: string, keeper: int]\n",
       "\u001b[36mimage\u001b[39m: \u001b[32mDataFrame\u001b[39m = [camera: int, whn: string ... 1 more field]\n",
       "\u001b[36mpermit\u001b[39m: \u001b[32mDataFrame\u001b[39m = [reg: string, sdate: string ... 1 more field]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "val camera = hiveCxt.table(\"sqlzoo.camera\")\n",
    "val keeper = hiveCxt.table(\"sqlzoo.keeper\")\n",
    "val vehicle = hiveCxt.table(\"sqlzoo.vehicle\")\n",
    "val image = hiveCxt.table(\"sqlzoo.image\")\n",
    "val permit = hiveCxt.table(\"sqlzoo.permit\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.\n",
    "List the owners (name and address) of Vehicles caught by camera 1 or 18 without duplication."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>name</th><th>address</th>\n",
       "                </tr>\n",
       "                <tr><td>Ambiguous, Arthur</td><td>Absorption Ave.</td></tr><tr><td>Inconspicuous, Iain</td><td>Interception Rd.</td></tr><tr><td>Strenuous, Sam</td><td>Surjection Street</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(keeper.withColumnRenamed(\"id\", \"keeper\")\n",
    " .join(vehicle, \"keeper\")\n",
    " .join(image.filter(image(\"camera\").isin(List(1, 18): _*)), \n",
    "       (vehicle(\"id\") === image(\"reg\")))\n",
    " .select(\"name\", \"address\")\n",
    " .distinct()\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.\n",
    "Show keepers (name and address) who have more than 5 vehicles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>name</th><th>address</th>\n",
       "                </tr>\n",
       "                <tr><td>Ambiguous, Arthur</td><td>Absorption Ave.</td></tr><tr><td>Inconspicuous, Iain</td><td>Interception Rd.</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(keeper.withColumnRenamed(\"id\", \"keeper\")\n",
    " .join(vehicle, \"keeper\")\n",
    " .groupBy(\"name\", \"address\")\n",
    " .agg(count(\"keeper\").alias(\"keeper\"))\n",
    " .filter(col(\"keeper\")>5)\n",
    " .select(\"name\", \"address\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.\n",
    "For each vehicle show the number of current permits (suppose today is the 1st of Feb 2007). The list should include the vehicle.s registration and the number of permits. Current permits can be determined based on charge types, e.g. for weekly permit you can use the date after 24 Jan 2007 and before 02 Feb 2007."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>reg</th><th>reg</th>\n",
       "                </tr>\n",
       "                <tr><td>SO 02 DSP</td><td>1</td></tr><tr><td>SO 02 DTP</td><td>1</td></tr><tr><td>SO 02 JSP</td><td>1</td></tr><tr><td>SO 02 KSP</td><td>1</td></tr><tr><td>SO 02 KTP</td><td>1</td></tr><tr><td>SO 02 QSP</td><td>1</td></tr><tr><td>SO 02 RSP</td><td>1</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(permit.withColumn(\"sdate\", to_timestamp(col(\"sdate\")))\n",
    " .withColumn(\"edate\", when(\n",
    "    col(\"chargetype\") === \"Daily\", col(\"sdate\") + expr(\"interval 1 day\")).when(\n",
    "    col(\"chargetype\") === \"Weekly\", col(\"sdate\") + expr(\"interval 1 week\")).when(\n",
    "    col(\"chargetype\") === \"Monthly\", col(\"sdate\") + expr(\"interval 1 month\")).when(\n",
    "    col(\"chargetype\") === \"Annual\", col(\"sdate\") + expr(\"interval 1 year\")))\n",
    " .filter((col(\"sdate\") <= \"2007-02-01\") && (col(\"edate\") >= \"2007-02-01\"))\n",
    " .groupBy(\"reg\")\n",
    " .agg(count(\"chargetype\").alias(\"reg\"))\n",
    " .orderBy(\"reg\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.\n",
    "Obtain a list of every vehicle passing camera 10 on 25th Feb 2007. Show the time, the registration and the name of the keeper if available."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>reg</th><th>whn</th><th>name</th>\n",
       "                </tr>\n",
       "                <tr><td>SO 02 CSP</td><td>2007-02-25 07:45:11.0</td><td>Ambiguous, Arthur</td></tr><tr><td>SO 02 ESP</td><td>2007-02-25 18:08:40.0</td><td>Ambiguous, Arthur</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(vehicle.join(keeper.withColumnRenamed(\"id\", \"keeper\"), \"keeper\")\n",
    " .join(image.filter((image(\"whn\").between(\"2007-02-25\", \"2007-02-26\")) &&\n",
    "                    (image(\"camera\") === 10)), (vehicle(\"id\") === image(\"reg\")))\n",
    " .select(\"reg\", \"whn\", \"name\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.\n",
    "List the keepers who have more than 4 vehicles and one of them must have more than 2 permits. The list should include the names and the number of vehicles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>name</th><th>n_vehicle</th>\n",
       "                </tr>\n",
       "                <tr><td>Inconspicuous, Iain</td><td>7</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[36mt\u001b[39m: \u001b[32mDataFrame\u001b[39m = [keeper: int]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// keepers who have more than 2 permits\n",
    "val t = (vehicle\n",
    "          .join(permit\n",
    "          .groupBy(\"reg\")\n",
    "          .agg(count(\"chargetype\").alias(\"npermit\"))\n",
    "          .filter(col(\"npermit\") > 2)\n",
    "          .select(\"reg\").alias(\"p\"), \n",
    "          (vehicle(\"id\") === col(\"reg\")))\n",
    "    .select(\"keeper\"))\n",
    "\n",
    "(vehicle.join(keeper.withColumnRenamed(\"id\", \"keeper\")\n",
    "              .join(t, \"keeper\"),\n",
    "              \"keeper\")\n",
    " .groupBy(\"name\")\n",
    " .agg(count(\"id\").alias(\"n_vehicle\"))\n",
    " .select(\"name\", \"n_vehicle\")\n",
    " .filter(col(\"n_vehicle\")>4)\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "spark.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.12.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
